var express = require('express');
var router = express.Router();
var User = require('./../sql/user');
var sql = require('./../sql');
var utils = require('./../utils')
var uuid = require('node-uuid');
var bcrypt = require('bcryptjs');
var jwt = require('jsonwebtoken');
var salt = bcrypt.genSaltSync(10); // 加密级别


/* GET users listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });

// 查询用户信息
router.get('/', (req, res, next) => {
  let { userid } = req.query;
  sql.find(User, { userid }, { _id: 0, password: 0 }).then(data => {
    if (data.length === 0) {
      res.send({
        code: '100',
        message: '没有该用户'
      })
    } else {
      res.send({
        code: '200',
        mesage: '查询成功',
        data: data
      })
    }
  })
})

// 修改用户名
router.post('/update/username', (req, res, next) => {
  let { userid, password, newname } = req.body;
  sql.find(User, { userid }, { _id: 0 }).then(data => {
    // 2.1 判断有么有该用户
    if (data.length === 0) {
      res.send({
        code: '100',
        message: '没有该用户'
      })
    } else {
      let pwd = data[0].password;
      var flag = bcrypt.compareSync(password, pwd) // 前为输入，后为数据库
      if (flag) {
        sql.update(User, { userid }, { username: newname }).then(data => {
          res.send({
            code: '200',
            message: '修改成功'
          })
        })
      } else {
        res.send({
          code: '300',
          message: '密码错误'
        })
      }
    }
  })
})

// 修改密码
router.post('/update/pwd', (req, res, next) => {
  let { userid, password, newpwd } = req.body;
  sql.find(User, { userid }, { _id: 0 }).then(data => {
    // 2.1 判断有么有该用户
    if (data.length === 0) {
      res.send({
        code: '100',
        message: '没有该用户'
      })
    } else {
      let pwd = data[0].password;
      var flag = bcrypt.compareSync(password, pwd) // 前为输入，后为数据库
      if (flag) {
        sql.update(User, { userid }, { password: newpwd }).then(data => {
          res.send({
            code: '200',
            message: '修改成功'
          })
        })
      } else {
        res.send({
          code: '300',
          message: '密码错误'
        })
      }
    }
  })
})

// 实现登录注册接口
router.post('/register-login', (req, res, next) => {
  let { password, tel } = req.body;
  // res.send(req.body)
  sql.find(User, { tel }, { _id: 0 }).then(data => {
    if (data.length === 0) {
      let userid = 'users_' + uuid.v1();
      let username = tel;
      // let email = '';
      password = bcrypt.hashSync(password, salt);
      // let token = jwt.sign({ userid }, 'ywx', {
      //   expiresIn: 60*0.1
      // })
      sql.insert(User, { userid, username, password, tel }).then(() => {
        // userid = data[0].userid;
        let token = jwt.sign({ userid }, 'ywx', {
          expiresIn: 60*60*24*30
        })
        res.send({
          code: '11111',
          message: '注册成功',
          token: token,
          userid
        })
      })
    } else {
      let pwd = data[0].password;
      var flag = bcrypt.compareSync(password, pwd);
      if (flag) {
        let userid = data[0].userid;
        let token = jwt.sign({ userid }, 'ywx', {
          expiresIn: 60*1
        })
        res.send({
          code: '10000',
          message: '登录成功',
          token: token,
          userid
        })
      } else {
        res.send(utils.passwordError)
      }
    }
  })
})

router.post('/login', (req, res, next) => {
  let { tel, password, signs } = req.body;
  sql.find(User, { tel }, { _id: 0 }).then(data => {
    // 2.1 判断有么有该用户
    if (data.length === 0) {
      // 2.2 没有该用户
      res.send(utils.unregister)
    } else {
      // 2.3 有该用户，验证密码
      // 2.3.1 获取数据库中的密码
      let pwd = data[0].password;
      // 2.3.2 比较 输入的 密码和数据库中的密码
      var flag = bcrypt.compareSync(password, pwd) // 前为输入，后为数据库
      if (flag) {
        // 2.3.3 密码正确,生成token
        let userid = data[0].userid
        let username = data[0].username
        if (signs) {
          signs = 24*7;
        } else {
          signs = 1;
        }
        let token = jwt.sign({ userid }, 'ywx', {
          // expiresIn: 60*60*24// 授权时效24小时
          expiresIn: 60*60*signs// 授权时效7天
        })
        res.send({
          code: '10010',
          message: '登陆成功',
          token: token,
          userid
        })
      } else {
        // 2.3.4 密码错误
        res.send({
          code: '10100',
          message: '密码错误'
        })
      }
    }
  })
})

router.get('/msg', (req, res, next) => {
  let { userid } = req.query;
  sql.find(User, { userid }, { _id: 0 }).then(data => {
    if (data.length === 0) {
      res.send(utils.unlogin)
    } else {
      let username = data[0].username;
      // let img = data[0].img ? data[0].img : 'https://static.smartisanos.cn/account/asset/img/default-user-avatar.png';
      // let reg = /(.{3}).*(.{4})/;
      // let username = data[0].username.replace(reg);
      res.send({
        code: '10020',
        username
        // img
      })
    }
  })
})

// router.post('/upload', upload.single('avatar'), function (req, res, next) {
//   console.log(req.file) // 包含的文件信息
//   console.log(req.body) // 文本域的信息
//   let userid = req.body.userid
//   // res.send(req.file)
//   let arr = req.file.originalname.split('.')
//   let type = arr[arr.length - 1] // 后缀名
  
//   let oldPath = req.file.destination + req.file.filename
//   let newPath = req.file.destination + req.file.filename + '.' + type
  
//   console.log(newPath)
//   fs.rename( oldPath , newPath , (err) => {
//     sql.update(User,{ userid:userid },{ $set:{userimg:newPath} }).then( res => {
//       console.log(111)
//     })
//     if (err) throw err;
//     res.send('上传成功')
//   })
// })

module.exports = router;
